Skip to content

Add inter-document attention masking to GPTDataset - #5298

Merged
asolergi-nv merged 3 commits into
NVIDIA:mainfrom
deepakn94:dnarayanan/pack_sequences_gpt_dataset
Jun 28, 2026
Merged

Add inter-document attention masking to GPTDataset#5298
asolergi-nv merged 3 commits into
NVIDIA:mainfrom
deepakn94:dnarayanan/pack_sequences_gpt_dataset

Conversation

@deepakn94

@deepakn94 deepakn94 commented Jun 11, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Add inter_document_masking config option to GPTDatasetConfig that computes cu_seqlens and max_seqlen from document boundaries within each sample, and resets position IDs per document.
  • Enable FlashAttention / TransformerEngine (and linear attention) to restrict attention to individual documents via the varlen (thd) path, replacing the legacy dense attention mask approach used by --reset-attention-mask.
  • Wire cu_seqlens / max_seqlen through TP broadcast (get_batch_on_this_tp_rank) so non-zero TP ranks receive the metadata.
  • Add --dataloader-inter-document-masking CLI argument.
  • Update FIMDataset._query_document_sample_shuffle_indices to return the 3-tuple expected by the new code path.
  • Enable context parallelism for inter-document masking via per-document CP balancing (_get_batch_on_this_cp_rank_per_document_balancing).
  • Pad cu_seqlens to a fixed length in GPTDataset so default_collate can stack samples with different numbers of documents when micro_batch_size > 1.

Results

8b_inter_document_masking_raw_metrics

8B-scale training runs (300B tokens) comparing baseline vs inter-document masking for both Transformer and Hybrid (Mamba+attention) architectures. Inter-document masking produces lower training and validation loss for both architectures, with no throughput regression. Gradient norms and parameter norms track closely between baseline and masking variants.

Test plan

  • Unit test (test_inter_document_masking) verifying cu_seqlens values, position ID resets, and max_seqlen across 20 samples.
  • Unit test (test_inter_document_masking_batch) verifying end-to-end get_batch with inter-document masking across TP and PP ranks (parametrized over TP={1,2,4} x PP={1,2,4}).
  • Unit test (test_hybrid_cp_batch) verifying CP partitioning with inter-document masking across TP, PP, and CP ranks.
  • Pad/strip round-trip tested via test_flatten_batch_for_packed_sequences_padded_cu_seqlens (on main via Merge cu_seqlens across micro-batch for THD attention #5454).
  • 8B training runs with --dataloader-inter-document-masking comparing loss curves against baseline (see Results above).

@copy-pr-bot

copy-pr-bot Bot commented Jun 11, 2026

Copy link
Copy Markdown

Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually.

Contributors can view more details about this message here.

@deepakn94
deepakn94 force-pushed the dnarayanan/pack_sequences_gpt_dataset branch from bbfb846 to f0d55be Compare June 11, 2026 21:39
@deepakn94

Copy link
Copy Markdown
Contributor Author

/claude review

Comment thread megatron/core/datasets/gpt_dataset.py
Comment thread megatron/core/utils.py Outdated
def get_batch_on_this_tp_rank(
batch: dict[str, torch.Tensor],
is_sft: bool,
is_packed: bool,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The parameter rename from is_sft to is_packed wasn't propagated to megatron/elastification/pretrain_hybrid_flex.py, which still calls get_batch_on_this_tp_rank(..., is_sft=is_sft, ...) at line 205. This will raise a TypeError at runtime.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two issues:

  1. Bug — padding not reflected in cu_seqlens (gpt_dataset.py): document_lengths is computed before padding is appended to sample_parts, so when a sample is shorter than sequence_length, cu_seqlens[-1] < sequence_length while tokens.shape[0] == sequence_length. FlashAttention varlen will either error or silently ignore tail positions.

  2. Broken caller (elastification/pretrain_hybrid_flex.py): Still passes is_sft=is_sft to get_batch_on_this_tp_rank after the parameter was renamed to is_packed. This will raise a TypeError at runtime.

@deepakn94

Copy link
Copy Markdown
Contributor Author

/claude review

Comment thread megatron/core/datasets/gpt_dataset.py
@deepakn94

Copy link
Copy Markdown
Contributor Author

/claude review

@deepakn94 deepakn94 changed the title Add pack_sequences option to GPTDataset for document-level cu_seqlens Add inter-document attention masking to GPTDataset Jun 15, 2026
Comment thread megatron/core/datasets/gpt_dataset.py
Comment thread megatron/core/utils.py Outdated

elif is_sft:
elif is_packed:
# NOTE(asolergi-nv): Broadcast required THD metadata for SFT to intermediate stages

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this NOTE (and the identical one at the other elif is_packed: branch below) still says "SFT" but now also applies to --dataloader-pack-sequences. Worth updating to mention packed sequences generally.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean PR — the rename from is_sft to is_packed is thorough and the new tests cover the important configurations well.

One potential correctness issue flagged inline: when a sample ends exactly at a document boundary, document_lengths[-1] -= 1 can produce a zero-length segment in cu_seqlens. See the inline comment on gpt_dataset.py for details and a suggested fix.

@deepakn94

Copy link
Copy Markdown
Contributor Author

/claude review

@deepakn94
deepakn94 marked this pull request as ready for review June 15, 2026 01:22
@deepakn94
deepakn94 requested review from a team as code owners June 15, 2026 01:22
@deepakn94
deepakn94 force-pushed the dnarayanan/pack_sequences_gpt_dataset branch from 6766317 to 1fd9d11 Compare June 15, 2026 01:24
@deepakn94

Copy link
Copy Markdown
Contributor Author

/claude review

Comment thread megatron/core/datasets/gpt_dataset.py

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clean PR overall — the is_sftis_packed rename is thorough, tests cover both the dataset and TP-broadcast paths, and the argument validation is in place.

One bug flagged inline: a zero-length cu_seqlens segment can occur when a sample boundary aligns exactly with a document boundary (the C helper sets doc_index_end_offset = 0, the extra-token-only part becomes length 0 after subtraction). See the inline comment for a suggested fix.

deepakn94 and others added 2 commits June 25, 2026 13:32
Compute cu_seqlens and max_seqlen from document boundaries within each
sample, and reset position IDs per document. This lets FlashAttention /
TransformerEngine (and linear attention) restrict attention to individual
documents via the varlen (thd) path, replacing the legacy dense attention
mask built by --reset-attention-mask.

Also updates FIMDataset._query_document_sample_shuffle_indices to return
the 3-tuple (sample, document_ids, document_lengths) expected by the new
code path.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Deepak Narayanan <dnarayanan@nvidia.com>
Add use_per_sequence_balancing parameter to get_batch_on_this_cp_rank so
inter-document masking routes through per-sequence zigzag partitioning
(document lengths are arbitrary and not divisible by 2 * cp_size).
Remove the CP > 1 assertion in arguments.py and pass the new flag from
all three pretrain entry points.

Extend test_inter_document_masking_batch to parametrize over cp_size and
add test_get_batch_on_this_cp_rank_per_sequence_balancing to verify
zigzag chunk selection with known token values.

Signed-off-by: Deepak Narayanan <dnarayanan@nvidia.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Signed-off-by: Deepak Narayanan <dnarayanan@nvidia.com>
@deepakn94

Copy link
Copy Markdown
Contributor Author

/claude review

Comment thread tests/unit_tests/data/test_gpt_dataset.py Outdated

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Light review — one bug found in the test, posted as an inline comment.

The production code changes look correct: the is_sfthas_cu_seqlens rename is consistently applied, the get_batch_on_this_cp_rank refactoring preserves existing behavior when use_per_sequence_balancing is False (the default), and the cu_seqlens/position-ID computation in __getitem__ handles the edge cases (empty last document after extra-token subtraction, padding shortfall) properly. No new direct process group access in megatron/core production code.

Signed-off-by: Deepak Narayanan <dnarayanan@nvidia.com>
@deepakn94

Copy link
Copy Markdown
Contributor Author

/claude review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/28275713645

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/28276368095

@svcnvidia-nemo-ci

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started!

You can track the progress here: https://github.com/NVIDIA/Megatron-LM/actions/runs/28317761167

@deepakn94

deepakn94 commented Jun 28, 2026

Copy link
Copy Markdown
Contributor Author

Note: context parallelism (--context-parallel-size > 1) is not yet supported with inter-document masking in pre-training. TE's THD ring attention assumes per-document load balancing, which requires each document length to be divisible by 2 * cp_size. #5531 adds a guard to assert context_parallel_size == 1 when inter-document masking is enabled.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Approved All necessary approvals have been made complexity: medium

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants